#include "sock_utils.h"

inline int
sock_readline (int fd, char *bufptr, size_t len, int flush)
{
  char *bufx = bufptr;
  static char *bp;
  static int cnt = 0;
  static char b[MSG_LEN_LIMIT];
  char c;
  int r_l;

  if (flush && cnt > 0)
  {
    r_l = cnt > len ? len : cnt;
    memcpy (bufptr, bp, r_l);
    cnt -= r_l;
    return r_l;
  }

  while (--len > 0)
  {
    if (--cnt <= 0)
    {
      cnt = recv (fd, b, sizeof (b), 0);
      if (cnt < 0)
	return -1;
      if (cnt == 0)
	return 0;
      bp = b;
    }
    c = *bp++;
    *bufptr++ = c;
    if (c == '\n')
    {
      *bufptr = '\0';
      return bufptr - bufx;
    }
  }
  return -1;
}

int
setNonblocking (int fd)
{
  int flags;
#if defined(O_NONBLOCK)
  if (-1 == (flags = fcntl (fd, F_GETFL, 0)))
    flags = 0;
  return fcntl (fd, F_SETFL, flags | O_NONBLOCK);
#else
  flags = 1;
  return ioctl (fd, FIOBIO, &flags);
#endif
}


